import React from "react";
import './TodoHeader.css';
import { useState } from "react";
import { useDispatch } from 'react-redux';
import { addTodo, asyncReqAddTodo } from "../../redux-n/slices/todoSlice";
import { nanoid } from "@reduxjs/toolkit";
export default function TodoHeader() {
  //声明一个状态
  let [keyword, setKeyword] = useState('');
  //获取 dispatch 函数
  let dispatch = useDispatch();
  //声明一个函数 keyup 事件回调
  let keyup = (e) => {
    if(e.keyCode === 13){
      //更新状态
      dispatch(asyncReqAddTodo({
        title: keyword,
        done: false,
      }))
      //清空文本框的内容
      setKeyword('');
    }
  }

  return (
    <div className="todo-header">
      <input 
          type="text" 
          value={keyword} 
          onKeyUp={keyup}
          onChange={(e) => {
            setKeyword(e.target.value)
          }}
          placeholder="请输入你的任务名称，按回车键确认" />
    </div>
  );
}
